package tests;

import java.util.Scanner;

public class FormatReader {
	Scanner scanner;

	public FormatReader(Scanner scanner) {
		this.scanner = scanner;
	}

	void invalid() {
		System.out.println("输入无效，请再试一次");
	}

	public String readStr(String prompt) {
		System.out.println(prompt);
		return scanner.next();
	}

	public double readDouble(String prompt) {
		while (true) {
			try {
				System.out.println(prompt);
				return scanner.nextDouble();
			} catch (Exception e) {
				invalid();
			} finally {
				scanner.nextLine();
			}
		}
	}

	int selectMenu(String[] choices) {
		return selectMenu(choices,false,false);
	}

	void showMenu(String[] choices, boolean ln) {
		for (String choice : choices) {
			System.out.print(choice);
			if (ln) System.out.println();
			else System.out.print("\t");
		}
		if (!ln) System.out.println();
	}

	int selectMenu(String[] choices, boolean ln, boolean startFromZero) {
		while (true) {
			try {
				System.out.println("********");
				showMenu(choices, ln);
				int result = scanner.nextInt();
				if (startFromZero) {
					if (choices[result] != null)
						System.out.println("********");
				} else if (choices[result - 1] != null) {
					System.out.println("*******");
				}
				return result;
			} catch (Exception e) {
				invalid();
			} finally {
				scanner.nextLine();
			}
		}
	}
}
